package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceSaveParam;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public List<GeofenceVO> select(GeofenceQuery geofenceQuery) {
        List<GeofenceVO> list = geofenceMapper.select(geofenceQuery);
        //车辆总数将围栏的车辆总数以及可用车辆总数查出并赋值
        for (int i=0; i < list.size(); i++) {
            GeofenceVO geofenceVO = list.get(i);
            VehicleQuery vehicleQuery = new VehicleQuery();
            vehicleQuery.setGeofenceId(geofenceVO.getId());
            List<VehicleVO> vehicleList = vehicleMapper.selectVehicle(vehicleQuery);
            int totalNum = vehicleList.size();
            int availableNum = 0;
            for(VehicleVO vehicleVO : vehicleList){
                if(vehicleVO.getStatus().equals("1")){
                    availableNum++;
                }
            }
            geofenceVO.setTotalNum(totalNum);
            geofenceVO.setAvailableNum(availableNum);
        }
        return list;
    }

    @Override
    public void insert(GeofenceSaveParam geofenceSaveParam) {
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceSaveParam,geofence);
        if(geofenceSaveParam.getId()==null){
            geofence.setStatus("1");
            geofence.setCreateTime(new Date());
            geofenceMapper.insert(geofence);
        }else{
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }
    }

    @Override
    public void delete(Long id) {
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        if(list.size()>0 && list!=null){
            throw new ServiceException(StatusCode.VEHICLE_EXISTS);
        }else {
            geofenceMapper.delete(id);
        }

    }
}
